﻿#!usr/bin/env python3
#-*- conding: utf-8 -*-

#第十九章 异步IO (代码虽然打完了,但是很不明白;2016年6月5日14:58:01)

import asyncio,threading

#把 generator(生成器)装饰为coroutine(协程)
@asyncio.coroutine 
def hello():
	print("hello word")
	r = yield from asyncio.sleep(1)
	print('Hello again!!')

#获取事件循环
loop1 = asyncio.get_event_loop()

loop1.run_until_complete(hello())

#多任务都是由一个线程并发执行,通过异步io操作
@asyncio.coroutine
def taskList():
	print("taskList 11 %s"%threading.currentThread())
	r = yield from asyncio.sleep(0.5)
	print("task list 22 %s" % threading.currentThread())


tasks = [taskList(),taskList()]

loop1.run_until_complete(asyncio.wait(tasks))

#loop1.close()


#用asyncio的异步网络连接来获取sina、sohu和163的网站首页：
def wget(host):
	print("wget %s"%host)
	connect = asyncio.open_connection(host,80)
	reader,writer=yield from connect
	header = "GET / HTTP/1.0/nHost:%s\r\n\r\n" % host
	writer.write(header.encode('utf-8'))
	yield from writer.drain()
	while True:
		line = yield from reader.readline()
		if line==b'\r\n':
			break
		print('%s header > %s' %(host,line.decode('utf-8').rstrip()))
	writer.close()

tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]

loop1 = asyncio.get_event_loop()
loop1.run_until_complete(asyncio.wait(tasks))

loop1.close()

'''
异步操作需要在coroutine中通过yield from完成；

多个coroutine可以封装成一组Task然后并发执行。
'''